package com.yksj.healthtalk.services;
/**
 * 
 * 后台服务处理请求
 * @author zhao
 * 
 */
public class MessagePushService{
	public static final String ACTION_REPEAT_STATE = "com.yksj.healthtalk.ui.ACTION_REPEAT_STATE";//兴趣墙转发状态返回
	public static final String ACTION_DOCTOR_CHARGE_STATE = "com.yksj.healthtalk.ui.ACTION_DOCTOR_CHARGE_STATE";//聊天中医生收费请求状态返回
	public static final String ACTION_FORBIDDENLIST = "com.yksj.healthtalk.services.ForbiddenlistAction";// 禁言列表
	public static final String ACTION_USERINFO_LOADCOMPLETE = "com.yksj.ui.ACTION_USERINFO_LOADCOMPLETE";// 加载用户个人资料完成
	public static final String ACTION_GETPERSONAL_INFO = "com.yksj.ui.ACTION_GETPERSONAL_INFO";// 加载客户信息完成
	public static final String ACTION_OFFLINE_MESSAGE = "com.yksj.ui.ACTION_OFFLINE_MESSAGE";//离线消息加载完成通知
	public static final String ACTION_STARTMUSIC_BACKGROUND = "com.yksj.ui.ACTION_STARTMUSIC_BACKGROUND";
	public static final String ACTION_COLLECT_FRIEND = "com.yksj.ui.FriendInfo";//处理与客户之间的关系
	public static final String ACTION_LOGIN = "com.yksj.healthtalk.services.LoginAction";// 登陆
	public static final String ACTION_COLLECT_GROUP = "com.yksj.ui.ACTION_COLLECT_GROUP";
	public static final String ACTION_JOIN_GROUP = "com.yksj.healthtalk.ACTION_JOIN_GROUP";// 加入聊天室通知
	public static final String ACTION_DOCTOR_INFO_AUDIT = "com.yksj.ui.ACTION_DOCTOR_INFO_AUDIT"; // 医师资料审核
	public static final String ACTION_CONNECTION_LOST = "com.yksj.ui.ACTION_CONNECTION_LOST"; // 连接丢失
	public static final String ACTION_COLLECT_GROUP_NOT = "com.yksj.ui.ACTION_COLLECT_GROUP_NOT";
	public static final String ACTION_FRIENDLIST = "com.yksj.ui.friendList";
	public static final String ACTION_MESSAGE_JOINROOM = "com.yksj.healthtalk.services.MessageaJoinRoomAction";// 加入房间通知
	public static final String ACTION_GROUP_ONLINE = "com.yksj.ui.ACTION_GROUP_ONLINE"; // 群在线成员
	public static final String ACTION_SEARCH_FRIEND_CON = "com.yksj.ui.FriendSearchCon";
	public static final String ACTION_GROUP_INVITE = "com.yksj.ui.ACTION_GROUP_INVITE"; // 群邀请
	public static final String ACTION_EXIT = "com.yksj.ui.EXIT";// 注销
	public static final String ACTION_GROUPLIST = "com.yksj.ui.groupList";
	public static final String ACTION_MODIFY_PERSONIF = "com.yksj.Health.PersonIn";// 修改个人资料
	public static final String ACTION_MESSAGE = "com.yksj.healthtalk.services.MessageaAction";// 新消息通知
	public static final String ACTION_PAY_MESSAGE = "com.yksj.healthtalk.services.PayMessageaAction";// 支付
	public static final String ACTION_LEAVE_WORD = "com.yksj.healthtalk.services.leaveWordsAction";//离线留言
	public static  final String ACTION_CHATTINGONLINEFRIEND = "com.yksj.ui.online.friend";//沙龙在线成员
	
	public static final String PARAME_KEY = "parame"; // 广播传值key
	public static final String BROAD_KEY = "result"; // 广播传值key
	
	/*private static final String TAG = "MessagePushService";
	private Looper mServiceLooper;
	private ServiceHandler mServiceHandler;
	private AppData mAppData;
	private final int KEEP_CONNECTION_TIME = 1000 * 15;// 保持连接握手请求
	private static final int WHAT_OTHERPLACE_LOGIN = -1;// 异地登陆
	private static final int WHAT_FORCELOGIN = -2;//强制重新登录
	public static final String PARAME_KEY = "parame"; // 广播传值key
	public static final String BROAD_KEY = "result"; // 广播传值key
	
	
	//private final int MessageTypeFriendAtt = 11; // 好友关注
	
	
	private final DecimalFormat mFormat = new DecimalFormat("0.00");
	ChatUserHelper mChatUserHelper;// 操作用户数据库
	SettingManager mSettingManager;
	protected final MessagePushBinder pushBinder = new MessagePushBinder();
	
	public class MessagePushBinder extends Binder {
		public MessagePushService getService() {
			return MessagePushService.this;
		}
	}
	
	*//**
	 * 异步更新ui线程
	 *//*
	private final Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case RequestCode.CHATTING_MESSAGE_SENDSTATE:
				final MessageEntity entity = (MessageEntity)msg.obj;
				onUpdateMesgeState(entity);
				break;
			//弹出框	
			case RequestCode.CODE_PRODUCT_CHANGE:
				String str = (String)msg.obj;
				onShowProductStateChangeDialog(str);
				break;
			}
		};
	};

	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			onDoServiceHandle(msg);
		}
	}
	
	*//**
	 * 后台服务线程处理
	 *//*
	private void onDoServiceHandle(Message msg) {
		switch (msg.what) {
		case RequestCode.KEEP_CONECTION_REQ:
			// 有网络的情况进行连接
			if (SystemUtils.isNetworkAvailable(getApplicationContext())) {
				// 判断当前的连接状态
				if (SmartFoxClient.isConnected()) {// 已经连接
					SmartFoxClient.sendKeepConnect();
				} else {// 没有连接的状况下
					SmartFoxClient.getSmartFoxClient().doConnecion();
				}
			}
			mServiceHandler.sendEmptyMessageDelayed(RequestCode.KEEP_CONECTION_REQ, KEEP_CONNECTION_TIME);
			break;
		case WHAT_OTHERPLACE_LOGIN:
			mServiceHandler.removeMessages(RequestCode.KEEP_CONECTION_REQ);
			DialogUtils.showLoginOutDialog(getApplicationContext()).show();
			break;
		case WHAT_FORCELOGIN://强制重新登录
			mServiceHandler.removeMessages(RequestCode.KEEP_CONECTION_REQ);
			DialogUtils.showForceLoginDialog(getApplicationContext()).show();
			break;
		case 1004://新消息通知
			int size = HTalkApplication.getNoReadMesgSize();
			if(size !=0) NotificationUtils.onNewMesgsNotification("未读消息"+size+"条");
			break;
		}
	}
	

	@Override
	public void onCreate() {
		super.onCreate();
		
		mAppData = HTalkApplication.getAppData();
		SmartFoxClient.initSmartFoxClient();
		SmartFoxClient.getSmartFoxClient().addEventHandler(this);
		
		HandlerThread handlerThread = new HandlerThread("HealthTalk");
		handlerThread.start();
		mServiceLooper = handlerThread.getLooper();
		mServiceHandler = new ServiceHandler(mServiceLooper);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if(intent == null)return;
		boolean isConnection = intent.getBooleanExtra("param", false);
		if (isConnection) {//是否需要去连接服务器
//			SmartFoxClient.sendConnection();
		}
	}

	@Override
	public void onDestroy() {
		LogUtil.d(TAG, "onDestroy");
		if (mServiceLooper != null)mServiceLooper.quit();
		mServiceHandler.removeMessages(RequestCode.KEEP_CONECTION_REQ);
//		SmartFoxClient.destorySmartFox();
		if (mChatUserHelper != null) {
			mChatUserHelper.close();
		}
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return pushBinder;
	}
	
	private void onSendBroadcast(String action, Object parame) {
		Intent intent = new Intent(action);
		if (parame != null) {
			if (parame instanceof Boolean) {
				intent.putExtra(PARAME_KEY, (Boolean) parame);
			} else if (parame instanceof String) {
				intent.putExtra(PARAME_KEY, (String) parame);
			} else if (parame instanceof Integer) {
				intent.putExtra(PARAME_KEY, (Integer) parame);
			}
		}
		sendBroadcast(intent);
	}

	*//**
	 * smartfox 响应
	 *//*
	@Override
	public void dispatch(BaseEvent event) throws SFSException {
		LogUtil.e(TAG, "smartfox dispatch event-------------------" + event.getType());
		if (event.getType().equals(SFSEvent.LOGIN)) {
			mSettingManager = SettingManager.getSettingManager(getApplicationContext());
			SmartFoxClient.sendJoinRoomReq();
			onSendBroadcast(SFSEvent.LOGIN, null);
			mServiceHandler.sendEmptyMessageDelayed(RequestCode.KEEP_CONECTION_REQ, KEEP_CONNECTION_TIME);
		} else if (event.getType().equals(SFSEvent.LOGIN_ERROR)) {
			Map<String, Object> map = event.getArguments();
			String code = String.valueOf(map.get("errorCode"));
			String errorMessage = (String) (map.get("errorMessage"));
			LogUtil.d(TAG, errorMessage);
			onLoginError(code);
		} else if (event.getType().equals(SFSEvent.LOGOUT)) {
			onLogOut(0);
		} else if (event.getType().equalsIgnoreCase(SFSEvent.CONNECTION_LOST)) {
			onSendBroadcast(SFSEvent.CONNECTION_LOST, null);
		} else if (event.getType().equals(SFSEvent.CONNECTION)) {
			Map<String, Object> arguments = event.getArguments();
			boolean isSuccess = (Boolean) arguments.get("success");// Connection
			if (isSuccess) {
				SmartFoxClient.sendRetLoginReq();
			}
			onSendBroadcast(SFSEvent.CONNECTION, isSuccess);
		} else if (event.getType().equals(SFSEvent.ROOM_JOIN)) {
			if(SmartFoxClient.getLoginUserInfo() == null){
				SmartFoxClient.sendLoadUserInfo();
			}else{
				onLoadOffMessge();
				Intent intent1 = new Intent(MessagePushService.ACTION_USERINFO_LOADCOMPLETE);
				intent1.putExtra("isShowProtocol",false);
				sendBroadcast(intent1);
			}
			onSendBroadcast(SFSEvent.ROOM_JOIN, null);
		} else if (event.getType().equals(SFSEvent.EXTENSION_RESPONSE)) {
			ISFSObject isfsObject = (ISFSObject) event.getArguments().get("params");
			String cmd = event.getArguments().get("cmd").toString();
			if (SmartFoxClient.EXTENTION_SMS_SYS_INITIALIZATION.equals(cmd)) {
				onExtensionEventHandler(isfsObject);
			}
		}
	}
	

	*//**
	 * smartfox 扩展请求
	 * @param isfsObject
	 *//*
	private void onExtensionEventHandler(ISFSObject isfsObject) {
		int code = isfsObject.getInt(SmartFoxClient.KEY_CODE);
		String value;
		switch (code) {
		case SmartFoxClient.RequestCode.LOGIN_OTHERPLACE:
			onLogOut(-1);
			break;
		// 客户基本资料
		case SmartFoxClient.RequestCode.CUSTOMER_INFO_REQ:
			//if(SmartFoxClient.getLoginUserInfo() != null){
				//更新客户资料
				String parame = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
				try {
					jsonObject = new JSONObject(parame);
					CustomerInfoEntity customerInfoEntity = DataParseUtil.JsonToCustmerInfo(jsonObject);
					SmartFoxClient foxClient = SmartFoxClient.getSmartFoxClient();
					foxClient.setCustomerInfoEntity(customerInfoEntity);
					foxClient.setUserId(customerInfoEntity.getId());
					foxClient.setUserMd5Id(customerInfoEntity.getId());
					foxClient.setUserName(customerInfoEntity.getUsername());
					HTalkApplication.getAppData().updateCacheInfomation(customerInfoEntity);
					mChatUserHelper = ChatUserHelper.getInstance();
					HttpRestClient.addHttpHeader("username", customerInfoEntity.getUsername());
					HttpRestClient.addHttpHeader("password", foxClient.getUserPas());
					loadingSalonOrGroupInfo();
					onLoadOffMessge();
				} catch (Exception e) {
					e.printStackTrace();
					LogUtil.d(TAG,"登陆客户基本资料加载异常");
				}
				boolean isShowProtocol = false;
				String parame = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
				try {
					JSONObject jsonObject = new JSONObject(parame);
					String str = jsonObject.optString("toShowCustomerProtocol","0");
					isShowProtocol = "1".equals(str);//jsonObject.optBoolean("toShowCustomerProtocol",false);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				String filterTypeStr = isfsObject.getUtfString("filteringType");//赛选类型
				updateFilterType(filterTypeStr);
				initLoginCustomerInfo(isfsObject, parame,mChatUserHelper);
				Intent intent1 = new Intent(MessagePushService.ACTION_USERINFO_LOADCOMPLETE);
				intent1.putExtra("isShowProtocol",isShowProtocol);
				sendBroadcast(intent1);
			break;
			// 收藏or删除健康友
		case SmartFoxClient.RequestCode.CODE_COLLECT_FRIEND:
			value = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
			sendBroad(ACTION_COLLECT_FRIEND, value);
			break;
		case SmartFoxClient.RequestCode.CODE_SEND_FACEBACK:
			value = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
			sendBroad("com.yksj.ui.ACTION_SEND_FACEBACK", value);
			break;
	
			//沙龙取消关注
		case SmartFoxClient.RequestCode.COLLECT_GROUP_NOT:
			value = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
			sendBroad(ACTION_COLLECT_GROUP_NOT, value);
			break;

			//沙龙关注 
		case SmartFoxClient.RequestCode.COLLECT_GROUP:
			value = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
			sendBroad(ACTION_COLLECT_GROUP, value);
			break;
		case SmartFoxClient.RequestCode.JOIN_GROUP_CHAT:// 加入群聊返回
			Collection<String> collection = isfsObject
					.getUtfStringArray(SmartFoxClient.KEY_PARAME);
			sendChattingJoinGroupBroad(collection.toString());
			break;
			// 注销
		case SmartFoxClient.RequestCode.SERVER_PARAME:
			int result = isfsObject.getInt(SmartFoxClient.KEY_PARAME);
			if(result == 1)stopSelf();
			Intent intent = new Intent(ACTION_EXIT);
			intent.putExtra(SmartFoxClient.KEY_PARAME,result);
			sendBroadcast(intent);
			break;
		//转发成功状态	
		case SmartFoxClient.RequestCode.CODE_REPEAT_MESSAGE:
			intent = new Intent(ACTION_REPEAT_STATE);
			String flag = isfsObject.getUtfString("FLAG");
			intent.putExtra("FLAG",flag);
			//生成消息对象
			if("Y".equals(flag)){
				if(isfsObject.containsKey("picture")){
					ISFSObject isfsObject1 = isfsObject.getSFSObject("picture");
					if(isfsObject1.containsKey("isGroupMessage") && isfsObject1.getInt("isGroupMessage") != 1){
						String pictureName = isfsObject1.getUtfString("dataHolder");
						MessageEntity messageEntity = new MessageEntity();
						messageEntity.setSenderId(SmartFoxClient.getLoginUserId());
						messageEntity.setDate(String.valueOf(System.currentTimeMillis()));
						messageEntity.setType(MessageEntity.TYPE_PICTURE);
						messageEntity.setSendFlag(true);
						messageEntity.setContent(pictureName);
						messageEntity.setSendState(MessageEntity.STATE_OK);
						intent.putExtra("picture",messageEntity);
					}
				}
				if(isfsObject.containsKey("text")){
					ISFSObject isfsObject1 = isfsObject.getSFSObject("picture");
					if(isfsObject1.containsKey("isGroupMessage") && isfsObject1.getInt("isGroupMessage") != 1){
						String content = isfsObject1.getUtfString("sms_req_content");
						MessageEntity messageEntity = new MessageEntity();
						messageEntity.setSenderId(SmartFoxClient.getLoginUserId());
						messageEntity.setDate(String.valueOf(System.currentTimeMillis()));
						messageEntity.setType(MessageEntity.TYPE_TEXT);
						messageEntity.setSendFlag(true);
						messageEntity.setContent(content);
						messageEntity.setSendState(MessageEntity.STATE_OK);
						intent.putExtra("text",messageEntity);
					}
				}
			}
			sendBroadcast(intent);
			break;
		case SmartFoxClient.RequestCode.CHATTING_GROUP_MESSAGE_RECEIVE://群消息
			onReceiveChatMesg(isfsObject,true);
			break;
		case SmartFoxClient.RequestCode.CHATTING_SINGLE_MESSAGE_RECEIVE://单聊消息
			onReceiveChatMesg(isfsObject,false);
			break;
		case SmartFoxClient.RequestCode.GROUP_INVITE:// 群邀请状态返回
			{
//				String sms_req_content = isfsObject.getUtfString("sms_req_content");//
//				String name = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
				intent = new Intent(ACTION_GROUP_INVITE);
				sendBroadcast(intent);
				//onReceiveChatMesg(isfsObject,false);
			}
			break;
		case SmartFoxClient.RequestCode.CHATTING_INVITE_RECEIVE:// 接收群邀请消息
			onReceiveChatMesg(isfsObject,false);
			break;
		case RequestCode.CHATTING_MESSAGE_SENDSTATE://消息发送状态返回
			onHandlerMesgeSendState(isfsObject);
			break;
		case SmartFoxClient.RequestCode.CODE_FORBIDWORDS_LIST:// 禁言列表返回
			Collection<String> collection2 = isfsObject.getUtfStringArray(SmartFoxClient.KEY_PARAME);
			String[] resultArray = new String[collection2.size()];
			collection2.toArray(resultArray);
			intent = new Intent(ACTION_FORBIDDENLIST);
			Bundle bundle = new Bundle();
			bundle.putStringArray(BROAD_KEY,resultArray);
			intent.putExtras(bundle);
			sendBroadcast(intent);
			break;
		case RequestCode.CODE_CHARGE_STATE://医生收费发送请求状态返回
			int state = isfsObject.getInt(SmartFoxClient.KEY_PARAME);
			intent = new Intent(ACTION_DOCTOR_CHARGE_STATE);
			intent.putExtra("state",state);
			sendBroadcast(intent);
			break;
		case RequestCode.CODE_CHARGE://医生收费请求
			String money = isfsObject.getUtfString("money");
			String time = isfsObject.getUtfString("time");
			String orid = isfsObject.getUtfString("orid");
			boolean isAccept = isfsObject.containsKey("CUSTOMER_GOLD");
			if(isAccept){//同意收费
				String customerGold = isfsObject.getUtfString("CUSTOMER_GOLD");
				if(NumberUtils.isNumber(customerGold)){
					SmartFoxClient.getLoginUserInfo().setMoney(NumberUtils.toInt(customerGold));
				}
			}
			String sms_target_id = isfsObject.getUtfString("sms_target_id");//发送者id
			intent = new Intent(ACTION_DOCTOR_CHARGE);
			intent.putExtra("money",money);
			intent.putExtra("time",time);
			intent.putExtra("orid",orid);
			intent.putExtra("sms_target_id",sms_target_id);
			sendBroadcast(intent);
			
			String content = isfsObject.getUtfString("content");
			MessageEntity messageEntity = new MessageEntity();
			messageEntity.setContent(content);
			messageEntity.setSenderId(sms_target_id);
			messageEntity.setReceiverId(SmartFoxClient.getLoginUserId());
			messageEntity.setType(MessageEntity.TYPE_TEXT);
			messageEntity.setSendFlag(false);
			messageEntity.setDownOrUpState(MessageEntity.STATE_OK);
			messageEntity.setDate(String.valueOf(System.currentTimeMillis()));
			mChatUserHelper.insertChatMessage(messageEntity);
			onUpdateMesgCllection(messageEntity,sms_target_id);
			intent = new Intent(MessagePushService.ACTION_MESSAGE);
			intent.putExtra("senderId",sms_target_id);//发送者id
			sendBroadcast(intent);
			break;
		case SmartFoxClient.RequestCode.CHATTING_ONLINE_FRIEND:{
			String value1 = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
			List<CustomerInfoEntity> entities = FriendHttpUtil.jsonAnalysisFriendEntity(value1, true);
			Intent intent2 = new Intent(ACTION_CHATTINGONLINEFRIEND);
			intent2.putExtra(BROAD_KEY,(ArrayList)entities);
			sendBroadcast(intent2);
			}//获取在线成员
			break;
		case SmartFoxClient.RequestCode.DOCTOR_INFO_AUDIT:
			value = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
			break;
		//订单变化通知
		case SmartFoxClient.RequestCode.CODE_PRODUCT_CHANGE:
			String content = isfsObject.getUtfString("content");
			Message message = mHandler.obtainMessage();
			message.obj = content;
			message.what = RequestCode.CODE_PRODUCT_CHANGE;
			mHandler.sendMessage(message);
			break;
		case SmartFoxClient.RequestCode.CODE_LEAVE_WORDS://留言条数
			String sizeStr = isfsObject.getUtfString(SmartFoxClient.KEY_PARAME);
			Intent intent2 = new Intent(ACTION_LEAVE_WORD);
			intent2.putExtra(BROAD_KEY,sizeStr);
			sendBroadcast(intent2);
			break;
		}
	}
	
	*//**
	 * 消息发送状态返回处理
	 * @param isfsObject
	 *//*
	private void onHandlerMesgeSendState(ISFSObject isfsObject) {
		// 1,0,群,单
		String serverId = isfsObject.getUtfString("serverId");
		String ISBUYTICK = isfsObject.getUtfString("ISBUYTICK");
		String tickNote = isfsObject.getUtfString("message");
		String customerId = isfsObject.getUtfString("sms_target_id");
		boolean isGroupMessage = isfsObject.getInt("isGroupMessage") == 1 ? true:false;
		int sendStatus = "0".equals(isfsObject.getUtfString("sendStatus")) ? 0 : 1;
		//int type = isfsObject.getInt("type");//消息类型
		//群聊	
		if(isGroupMessage){//更新本地数据库消息状态
			String sid = isfsObject.getUtfString("sid");
			final MessageEntity entity = mAppData.getSendCacheMessageEntity(serverId);
			if(entity != null){
				mAppData.getSendMesgeCache().remove(serverId);
				entity.setId(sid);
				entity.setSendState(sendStatus);
				Message msg = mHandler.obtainMessage();
				msg.what = RequestCode.CHATTING_MESSAGE_SENDSTATE;
				msg.obj = entity;
				mHandler.sendMessage(msg);
			}
		}else{
			MessageEntity entity = mAppData.getSendCacheMessageEntity(serverId);
			if(entity == null){
				entity = new MessageEntity();
				entity.setId(serverId);
			}
			entity.setSendState(sendStatus);
			mChatUserHelper.updateChatMessageSendState(entity);
			Message msg = mHandler.obtainMessage();
			msg.what = RequestCode.CHATTING_MESSAGE_SENDSTATE;
			msg.obj = entity;
			mHandler.sendMessage(msg);
			
			//提示购买服务
			if("1".equals(ISBUYTICK)){
				Intent intent = new Intent(MessagePushService.ACTION_PAY_MESSAGE);
				intent.putExtra("senderId", customerId);
				intent.putExtra("tickNote", tickNote);
				sendBroadcast(intent);
			}
		}
	}
	
	*//**
	 * 接收聊天消息
	 * @param isfsObject
	 * @param isGroupChat 聊天类型
	 *//*
	private void onReceiveChatMesg(ISFSObject isfsObject,boolean isGroupMesg){
		//
		int type = isfsObject.getInt("type");
		MessageEntity messageEntity = new MessageEntity();
		String id = isfsObject.getUtfString("serverId");//消息id
		String time = isfsObject.getUtfString("timeStamp");//时间
		messageEntity.setServerId(id);
		messageEntity.setId(id);
		messageEntity.setDate(TimeUtil.pareTime(time));
		// 图片
		if (type == MessageEntity.TYPE_PICTURE) {
			String pictureName = isfsObject.getUtfString("dataHolder");
			messageEntity.setSendFlag(false);
			messageEntity.setType(MessageEntity.TYPE_PICTURE);
			messageEntity.setSenderId(isfsObject.getUtfString("customerId"));
			messageEntity.setDownOrUpState(MessageEntity.STATE_NORMAL);
			messageEntity.setContent(pictureName);
			// 语音
		} else if (type == MessageEntity.TYPE_VOICE) {
			messageEntity.setContent(isfsObject.getUtfString("dataHolder"));
			messageEntity.setSendFlag(false);
			messageEntity.setType(MessageEntity.TYPE_VOICE);
			messageEntity.setSenderId(isfsObject.getUtfString("customerId"));
			messageEntity.setDownOrUpState(MessageEntity.STATE_NORMAL);
			messageEntity.setVoiceLength(mFormat.format(isfsObject.getFloat("duration")));
			// 文字
		} else if (type == MessageEntity.TYPE_TEXT) {
			String customerId = isfsObject.getUtfString("customerId");
			messageEntity.setSendFlag(false);
			messageEntity.setSenderId(customerId);
			messageEntity.setDownOrUpState(MessageEntity.STATE_OK);
			messageEntity.setType(type);
			messageEntity.setContent(isfsObject.getUtfString("sms_req_content"));
			if(isfsObject.containsKey(SmartFoxClient.KEYWORDS)){// && collection.size() != 0 && !SmartFoxClient.helperId.equals(customerId)
				JSONArray array;
				try {
					Collection<String> collection  = isfsObject.getUtfStringArray(SmartFoxClient.KEYWORDS);
					array = new JSONArray(collection.toString());
					messageEntity.setContentJsonArray(array);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			//医生审核
			if(SmartFoxClient.helperId.equals(customerId)){
				String dataHolder = isfsObject.getUtfString("dataHolder");
				if(dataHolder != null){
					if(NumberUtils.isNumber(dataHolder)){
						SmartFoxClient.getLoginUserInfo().setRoldid(NumberUtils.toInt(dataHolder));
					}
				}
			}
			// 坐标
		} else if (type == MessageEntity.TYPE_LOCATION) {
			String dataHolder = isfsObject.getUtfString("dataHolder");
			String address = isfsObject.getUtfString("sms_req_content");
			messageEntity.setAddress(address);
			messageEntity.setContent(dataHolder);
			messageEntity.setSendFlag(false);
			messageEntity.setType(MessageEntity.TYPE_LOCATION);
			messageEntity.setSenderId(isfsObject.getUtfString("customerId"));
			messageEntity.setDownOrUpState(MessageEntity.STATE_NORMAL);
			//好友关注
		} else if (type == 11) {
			//String userId = isfsObject.getUtfString("customerId");// 关注者id
			return;
		}else if(type == MessageEntity.TYPE_INVITATION){//邀请,关注
			String sms_req_content = isfsObject.getUtfString("sms_req_content");
			Collection<String> collection  = isfsObject.getUtfStringArray(SmartFoxClient.KEYWORDS);
			messageEntity.setSenderId(SmartFoxClient.helperId);
			messageEntity.setReceiverId(SmartFoxClient.getLoginUserId());
			messageEntity.setSendFlag(false);
			messageEntity.setContent(collection.toString());
			if(collection == null){
				messageEntity.setContent(sms_req_content);
			}else{
				JSONArray array;
				try {
					array = new JSONArray(collection.toString());
					messageEntity.setContentJsonArray(array);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			messageEntity.setType(MessageEntity.TYPE_TEXT);
			messageEntity.setDate(String.valueOf(System.currentTimeMillis()));
			mChatUserHelper.insertChatMessage(messageEntity);
			onUpdateMesgCllection(messageEntity,SmartFoxClient.helperId);
			Intent intent1 = new Intent(MessagePushService.ACTION_MESSAGE);
			intent1.putExtra("senderId",SmartFoxClient.helperId);//发送者id
			sendBroadcast(intent1);
			return;
		//医生资质审核	
		}else if(type == 12){
			float state = isfsObject.getFloat("duration");
			String sms_req_content = isfsObject.getUtfString("sms_req_content");
//			if(state == 1){//成功需要更新客户资料
			SmartFoxClient.sendLoadUserInfo();
			messageEntity.setSenderId(SmartFoxClient.helperId);
			messageEntity.setReceiverId(SmartFoxClient.getLoginUserId());
			messageEntity.setSendFlag(false);
			messageEntity.setContent(sms_req_content);
			messageEntity.setType(MessageEntity.TYPE_TEXT);
			messageEntity.setDate(String.valueOf(System.currentTimeMillis()));
			mChatUserHelper.insertChatMessage(messageEntity);
//			onUpdateMesgCllection(messageEntity,SmartFoxClient.helperId);
			Intent intent1 = new Intent(MessagePushService.ACTION_MESSAGE);
			intent1.putExtra("senderId",SmartFoxClient.helperId);//发送者id
			sendBroadcast(intent1);
			return;
		}
		String targetId = isfsObject.getUtfString("sms_target_id");
		String customerId = isfsObject.getUtfString("customerId");
		messageEntity.setSenderId(customerId);
		messageEntity.setReceiverId(targetId);
		if (isGroupMesg) {//群聊消息
			onUpdateMesgCllection(messageEntity,targetId);
			messageEntity.setGroupId(targetId);
			Intent intent = new Intent(MessagePushService.ACTION_MESSAGE);
			intent.putExtra("senderId",targetId);//发送者id
			sendBroadcast(intent);
		} else {//单聊消息
			mChatUserHelper.insertChatMessage(messageEntity);
			onUpdateMesgCllection(messageEntity,customerId);
			Intent intent = new Intent(MessagePushService.ACTION_MESSAGE);
			intent.putExtra("senderId",customerId);//发送者id
			sendBroadcast(intent);
		}
	}
	
	private void onUpdateMesgCllection(MessageEntity entity,String userid){
		List<MessageEntity> list = mAppData.messageCllection.get(userid);
		if(list == null){
			list = new ArrayList<MessageEntity>();
		}
		list.add(entity);
		mAppData.messageCllection.put(userid,list);
		mServiceHandler.sendEmptyMessage(1004);
	}

	*//**
	 * 我的沙龙和我的社交的信息
	 *//*
	private void loadingSalonOrGroupInfo() {
		HttpRestClient.doHttpLoginAboutMe(SmartFoxClient.getSmartFoxClient().getUserId(),new ObjectHttpResponseHandler() {
			@Override
			public Object onParseResponse(String cotent) {
				AppData appData = HTalkApplication.getAppData();
				JsonParseUtils.LoginInitSalon(getApplicationContext(),cotent,appData);
				return null;
			}
		});
	}
	
	*//**
	 * 加载离线消息
	 *//*
	private void onLoadOffMessge(){
		HttpRestClient.doHttpLoadOffMessage(SmartFoxClient.getLoginUserId(),new ObjectHttpResponseHandler() {
			@Override
			public Object onParseResponse(String content) {
				JsonParseUtils.parseOffMessage(content);
				mServiceHandler.sendEmptyMessage(1004);
				//离线消息加载完成通知
				Intent intent = new Intent(ACTION_OFFLINE_MESSAGE);
				sendBroadcast(intent);
				return null;
			}
		});
	}

	*//**
	 * 请求登陆客户资料
	 * @param value
	 *//*
	private void initLoginCustomerInfo(ISFSObject isfsObject, String parame,ChatUserHelper mDictionaryHelper) {
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(parame);
			CustomerInfoEntity customerInfoEntity = DataParseUtil.JsonToCustmerInfo(jsonObject);
			SmartFoxClient foxClient = SmartFoxClient.getSmartFoxClient();
			foxClient.setCustomerInfoEntity(customerInfoEntity);
			foxClient.setUserId(customerInfoEntity.getId());
			foxClient.setUserMd5Id(customerInfoEntity.getId());
			foxClient.setUserName(customerInfoEntity.getUsername());
			
			mChatUserHelper = ChatUserHelper.getInstance();
			HTalkApplication.getAppData().updateCacheInfomation(customerInfoEntity);
			HttpRestClient.addHttpHeader("username", customerInfoEntity.getUsername());
			HttpRestClient.addHttpHeader("password", foxClient.getUserPas());
			loadingSalonOrGroupInfo();
			onLoadOffMessge();
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.d(TAG,"登陆客户基本资料加载异常");
		}
		LogUtil.d(TAG,"客户基本资料加载完成");
	}

	*//**
	 * 加入到聊天室通知
	 * 
	 * @param id
	 *//*
	private void sendChattingJoinGroupBroad(String value) {
		Intent intent = new Intent(MessagePushService.ACTION_JOIN_GROUP);
		intent.putExtra("value", value);
		getApplicationContext().sendBroadcast(intent);
	}
	
	
	*//**
	 * 更新筛选类型
	 * 
	 * @param type
	 *//*
	private void updateFilterType(String filterTypeStr) {
		String[] types = filterTypeStr.split("&");
		boolean[] filterType = mSettingManager.getFilterType();
		for (int i = 0; i < types.length; i++) {
			try {
				int type = 0;
				if(NumberUtils.isNumber(types[i])){
					type = Integer.parseInt(types[i]);
					if (type < filterType.length)
						filterType[type] = true;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		mSettingManager.setFilterType(filterType);
	}
	
	*//**
	 * 发送聊天消息
	 * @param entity
	 *//*
	public void onSendChatMessage(MessageEntity entity,boolean isGroupChat,int type){
		onSaveMesage(entity,isGroupChat);
		switch(type){
		case MessageEntity.TYPE_TEXT://文本发送
			SmartFoxClient.sendChatMessage(entity.getId(),entity.getReceiverId()
					,isGroupChat,type,0,entity.getContent(),null,null,null);
			break;
		case MessageEntity.TYPE_VOICE:
			HttpRestClient.doHttpSendChatVoiceMesg(entity,isGroupChat,new ChatVoiceUploadHttpHandler(entity,isGroupChat)); 
			break;
		case MessageEntity.TYPE_PICTURE://图片发送
			HttpRestClient.doHttpSendChatImageMesg(entity,isGroupChat,new ChatImageUploadHttpHandler(entity,isGroupChat));
			break;
		case MessageEntity.TYPE_LOCATION://地图发送
			SmartFoxClient.sendChatMessage(entity.getId(),entity.getReceiverId(),isGroupChat, 
					MessageEntity.TYPE_LOCATION, 0, 
					entity.getAddress(), 
					null,null,entity.getContent());
			break;
		}
	}
	
	*//**
	 * 
	 * 保存消息到缓存
	 * @param entity
	 * @param isGroupChat
	 * 
	 *//*
	private void onSaveMesage(MessageEntity entity,boolean isGroupChat){
		if(isGroupChat)entity.setId(String.valueOf(System.currentTimeMillis()));
		mAppData.getSendMesgeCache().put(entity.getId(),entity);
	}
	
	*//**
	 * 发送广播
	 * @param action
	 * @param value
	 *//*
	private void sendBroad(String action, String value) {
		Intent intent = new Intent(action);
		intent.putExtra(BROAD_KEY, value);
		sendBroadcast(intent);
	}
	
	*//**
	 * 登陆错误处理
	 *//*
	private void onLoginError(String errorCode) {
		if("3".equals(errorCode)){//用户名或者密码错误
		}else if("6".equals(errorCode)){//需要重新登录
			mServiceHandler.sendEmptyMessage(WHAT_FORCELOGIN);
		}else if("7".equals(errorCode)){
		}
		onSendBroadcast(SFSEvent.LOGIN_ERROR, errorCode);
	}
	
	*//**
	 * 登出
	 * @param type
	 *//*
	private void onLogOut(int type) {
		switch(type){
		case 0://正常退出
			break;
		case -1://异地登陆被迫下线
			mServiceHandler.sendEmptyMessage(WHAT_OTHERPLACE_LOGIN);
			break;
		}
	}
	
	*//**
	 * 聊天语音发送
	 * @author zhao
	 *//*
	class ChatVoiceUploadHttpHandler extends ObjectHttpResponseHandler{
		final MessageEntity mEntity;
		final boolean mIsGroupChat;
		int sendState = 0;//发送状态
		public ChatVoiceUploadHttpHandler(MessageEntity entity,boolean isGroupChat){
			mEntity = entity;
			mIsGroupChat = isGroupChat;
		}
		@Override
		public Object onParseResponse(String cotent) {
			try {
				if("0".equals(cotent)){
					sendState = MessageEntity.STATE_FAIL;
					mEntity.setSendState(sendState);
				}else{
					JSONObject response = new JSONObject(cotent);
//					String serverId = response.getString("serverId");
//					String sid = response.getString("sid");
					String dataHolder = response.getString("dataHolder");
					File file = new File(StorageUtils.getVoicePath(),mEntity.getContent());
					String filePath = file.getParent();
					String name = StorageUtils.getFileName(dataHolder);
					file.renameTo(new File(filePath,name));
					mEntity.setContent(name);
					sendState = MessageEntity.STATE_OK;
					mEntity.setSendState(sendState);
					mAppData.removeSendMesgeCache(mEntity);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				sendState = MessageEntity.STATE_FAIL;
			}
			mEntity.setSendState(sendState);
			if(!mIsGroupChat)mChatUserHelper.updateChatMessageSendStateAndContent(mEntity);
			return null;
		}
		@Override
		public void onFinish() {
			mAppData.removeSendMesgeCache(mEntity);
			onUpdateMesgeState(mEntity);
		}
		@Override
		public void onFailure(Throwable error, String content) {
			mEntity.setSendState(sendState);
		}
	}
	
	*//**
	 * 聊天图片发送
	 * @author zhao
	 *//*
	class ChatImageUploadHttpHandler extends ObjectHttpResponseHandler{
		final MessageEntity mEntity;
		final boolean mIsGroupChat;
		int sendState = 0;//发送状态
		public ChatImageUploadHttpHandler(MessageEntity entity,boolean isGroupChat) {
			this.mEntity = entity;
			this.mIsGroupChat = isGroupChat;
		}
		@Override
		public Object onParseResponse(String cotent) {
			try {
				if("0".equals(cotent)){
					sendState = MessageEntity.STATE_FAIL;
					mEntity.setSendState(MessageEntity.STATE_FAIL);
				}else{
					JSONObject response = new JSONObject(cotent);
					String serverId = response.getString("serverId");
					String sid = response.getString("sid");
					String dataHolder = response.getString("dataHolder");
					String sendStatus = response.getString("sendStatus");
					//上传完成之后需要重新命名
					ImageLoader loader = ImageLoader.getInstance();
					String rootPath = StorageUtils.getImagePath();
					String oldPaths[] = mEntity.getContent().split("&");
					String newPaths[] = dataHolder.split("&");
					File rootFilePath = new File(rootPath);
					//小文件重新命名
					File oldFile = loader.getOnDiscFileName(rootFilePath,oldPaths[0]);
					File newFile = loader.getOnDiscFileName(rootFilePath,newPaths[0]);
					oldFile.renameTo(newFile);
					//大文件重新命名
					oldFile = loader.getOnDiscFileName(rootFilePath,oldPaths[1]);
					newFile = loader.getOnDiscFileName(rootFilePath,newPaths[1]);
					oldFile.renameTo(newFile);
					mEntity.setContent(dataHolder);
					sendState = "0".equals(sendStatus) ? MessageEntity.STATE_FAIL:MessageEntity.STATE_OK;
					mAppData.removeSendMesgeCache(mEntity);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				sendState = MessageEntity.STATE_FAIL;
			}
			mEntity.setSendState(sendState);
			if(!mIsGroupChat)mChatUserHelper.updateChatMessageSendStateAndContent(mEntity);
			return null;
		}
		@Override
		public void onFinish() {
			mAppData.removeSendMesgeCache(mEntity);
			onUpdateMesgeState(mEntity);
		}
	}
	
	*//**
	 * 更新消息发送状态
	 * @param entity
	 * @param state
	 *//*
	private void onUpdateMesgeState(MessageEntity entity){
		final int state  = entity.getSendState();
		if(entity.viewHolder != null){
			ViewHolder holder = entity.viewHolder.get();
			if(holder == null)return;
			CheckBox checkBox = holder.stateCheckbV;
			if(checkBox == null)return;
			if(state == MessageEntity.STATE_FAIL){
				checkBox.setChecked(false);
				checkBox.setText("发送失败");
			}else if(state == MessageEntity.STATE_OK){
				checkBox.setText("发送成功");
				checkBox.setChecked(true);
			}else if(state == MessageEntity.STATE_PROCESING){
				checkBox.setText("发送中");
				checkBox.setChecked(false);
			}
		}
	}
	
	Dialog mDialog;
	private void onShowProductStateChangeDialog(String content){
		if(mDialog == null){
			final Dialog dialog = new Dialog(this, R.style.dialog);
			dialog.setCanceledOnTouchOutside(false);
			View view = LayoutInflater.from(this).inflate(R.layout.dialog,null);
			Button button = (Button) view.findViewById(R.id.dialog_btn);
			button.setText(R.string.sure);
			button.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			DisplayMetrics display = getResources().getDisplayMetrics();
			int width = display.widthPixels - 50;
			int height = LayoutParams.WRAP_CONTENT;
			dialog.setContentView(view,new LayoutParams(width, height));
			dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			mDialog = dialog;
		}
		if(mDialog.isShowing()){
			mDialog.dismiss();
		}
		((TextView)mDialog.findViewById(R.id.dialog_text)).setText(content);
		mDialog.show();
	}*/
}	